package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.dto.PageRequest;
import example.springboot.dto.PageResult;
import example.springboot.dto.WordDTO;
import example.springboot.dto.ImportResult;
import example.springboot.entity.Word;
import example.springboot.service.WordService;
import example.springboot.util.SystemLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/admin/words")
@CrossOrigin
public class WordController {

    @Autowired
    private WordService wordService;

    /**
     * 获取单词列表（分页）
     */
    @GetMapping
    public Result<PageResult<WordDTO>> getWordList(PageRequest pageRequest) {
        try {
            PageResult<WordDTO> result = wordService.getWordList(pageRequest);
            return Result.success(result);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取单词列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取单词详情
     */
    @GetMapping("/{id}")
    public Result<Word> getWordById(@PathVariable Integer id) {
        try {
            Word word = wordService.findById(id);
            if (word == null) {
                return Result.error("单词不存在");
            }
            return Result.success(word);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取单词详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建单词
     */
    @PostMapping
    public Result<Word> createWord(@RequestBody Word word) {
        try {
            // 验证必填字段
            if (word.getWord() == null || word.getWord().trim().isEmpty()) {
                return Result.error("单词不能为空");
            }
            if (word.getMeaning() == null || word.getMeaning().trim().isEmpty()) {
                return Result.error("释义不能为空");
            }

            Word createdWord = wordService.createWord(word);
            // 记录操作日志
            SystemLogUtil.logOperation("创建单词", "创建了单词: " + word.getWord());
            return Result.success("创建成功", createdWord);
        } catch (RuntimeException e) {
            // 记录错误日志
            SystemLogUtil.logError("创建单词失败", "创建单词失败: " + e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 检查是否是唯一约束违反
            if (e.getMessage() != null && e.getMessage().contains("Duplicate entry")) {
                SystemLogUtil.logError("创建单词失败", "单词\"" + word.getWord() + "\"已存在，无法重复添加");
                return Result.error("单词\"" + word.getWord() + "\"已存在，无法重复添加");
            }
            // 记录错误日志
            SystemLogUtil.logError("创建单词失败", "创建单词失败: " + e.getMessage());
            return Result.error("创建单词失败：" + e.getMessage());
        }
    }

    /**
     * 更新单词信息
     */
    @PutMapping("/{id}")
    public Result<String> updateWord(@PathVariable Integer id, @RequestBody Word word) {
        try {
            word.setId(id);
            boolean success = wordService.updateWord(word);
            if (success) {
                // 记录操作日志
                SystemLogUtil.logOperation("编辑单词", "编辑了单词ID: " + id);
                return Result.success("更新成功");
            } else {
                // 记录错误日志
                SystemLogUtil.logError("编辑单词失败", "编辑单词ID: " + id + " 失败");
                return Result.error("更新失败");
            }
        } catch (RuntimeException e) {
            // 记录错误日志
            SystemLogUtil.logError("编辑单词失败", "编辑单词ID: " + id + " 失败: " + e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 记录错误日志
            SystemLogUtil.logError("编辑单词失败", "编辑单词ID: " + id + " 失败: " + e.getMessage());
            return Result.error("更新单词失败：" + e.getMessage());
        }
    }

    /**
     * 删除单词
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteWord(@PathVariable Integer id) {
        try {
            boolean success = wordService.deleteWord(id);
            if (success) {
                // 记录操作日志
                SystemLogUtil.logOperation("删除单词", "删除了单词ID: " + id);
                return Result.success("删除成功");
            } else {
                // 记录错误日志
                SystemLogUtil.logError("删除单词失败", "删除单词ID: " + id + " 失败");
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 记录错误日志
            SystemLogUtil.logError("删除单词失败", "删除单词ID: " + id + " 失败: " + e.getMessage());
            return Result.error("删除单词失败：" + e.getMessage());
        }
    }

    /**
     * 批量导入单词
     * 返回详细的导入结果，包括成功数量、跳过数量、错误数量等
     */
    @PostMapping("/import")
    public Result<ImportResult> importWords(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            String fileName = file.getOriginalFilename();
            if (fileName == null || !fileName.endsWith(".xlsx")) {
                return Result.error("只支持.xlsx格式的Excel文件");
            }

            ImportResult result = wordService.importWords(file);
            String message = result.getMessage();
            
            // 记录操作日志
            if (result.getSuccessCount() > 0) {
                SystemLogUtil.logOperation("批量导入", "批量导入单词: " + message);
            } else if (result.getSkipCount() > 0) {
                SystemLogUtil.logOperation("批量导入", "批量导入单词: " + message);
            } else {
                SystemLogUtil.logError("批量导入失败", "批量导入单词失败: " + message);
            }
            
            // 返回详细的导入结果数据，前端可以获取 successCount、skipCount、errorCount、errors 等信息
            return Result.success(message, result);
        } catch (RuntimeException e) {
            // 记录错误日志
            SystemLogUtil.logError("批量导入失败", "批量导入单词失败: " + e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 记录错误日志
            SystemLogUtil.logError("批量导入失败", "批量导入单词失败: " + e.getMessage());
            return Result.error("导入失败：" + e.getMessage());
        }
    }
}

